package com.cunyu.listener;


import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cunyu.action.OpenController;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.tom.kit.cache.TimedCache;

public class BaseInterceptor implements HandlerInterceptor{
	
	static Log log = LogFactory.getLog("AuthInterceptor");
	
	@Resource
	private TimedCache<String, Object> timedCache;
	
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
		RequestContext.begin(req, res);
		req.setCharacterEncoding("UTF-8");
		if(handler instanceof OpenController){
			OpenController controller = (OpenController)handler;
			return controller.before(req, res);
		}
		return false;
	}

	public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView mode) throws Exception {
		try{
			if(mode!=null&&!mode.getViewName().startsWith("redirect:")){
				mode.addObject("app", Constants.apps);
				Cookie cookie = RequestContext.get().getCookie("token");
				if (cookie != null)
					mode.addObject("muser", timedCache.get(cookie.getValue()));
				String uri = req.getRequestURI();
				mode.addObject("reqURI",uri) ;
			}
		}finally{
			long time = System.currentTimeMillis()-RequestContext.get().i;
			log.info( handler +"::"+req.getRequestURI()+ "::timeline::"+ time);
			RequestContext.get().end(); 
		}
	}

	public void afterCompletion(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse, Object paramObject, Exception paramException) throws Exception {
		
	}
	
	public static class NumUtil {
		public static String format2f(Object a){
			String result = String.format("%.2f", Double.parseDouble(a.toString()));
			return result;
		}
		
	}

}
